//
//  DownloadListDAO.m
//  ImGuider
//
//  Created by llt on 2017/4/26.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "DownloadListDAO.h"
#import "DBHelper.h"

#define TABLE_NAME [UserManager userMd5IdentiferPath:@"download_list_v2"]

#define SID @"_id" // 本地数据库ID

#define UNION_ID @"union_id"

#define DOWNLOAD_TIME @"download_time"// 下载时间
#define UPDATE_TIME @"update_time"// 更新时间

#define JSON @"json"// 数据json
#define SUSPEND @"suspend"// 数据json

@implementation DownloadListDAO

//-----------------------------------路线表------------------------------------------
+ (void)createTabWithDB:(FMDatabase *)db {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *deleteSql = [NSString stringWithFormat:@"drop table %@",[UserManager userMd5IdentiferPath:@"download_list"]];
        [db executeUpdate:deleteSql];
    });
    
    NSString *sqlStr = [NSString stringWithFormat:@"create table if not exists %@(%@ integer not null primary key autoincrement, %@ text not null unique, %@ date, %@ date, %@ text, %@ integer)",TABLE_NAME,SID,UNION_ID,DOWNLOAD_TIME,UPDATE_TIME,JSON,SUSPEND];
    
    [db executeUpdate:sqlStr];
}

+ (LineModel *)getLineModelWithRS:(FMResultSet *)set {
    
    NSString *json = [set stringForColumn:JSON];
    
    if (json.length == 0) {
        
        return nil;
    }
    LineModel *model = [LineModel modelWithJSON:json];
    
    if (!model) {
        
        [NetAPIManager postPhoneData:@{@"ios_error":json}];
        return nil;
    }
    
    model.downloadTime = [set dateForColumn:DOWNLOAD_TIME];
    model.updateTime = [set dateForColumn:UPDATE_TIME];
    model.isSuspend = [set boolForColumn:SUSPEND];
    
    return model;
}


+ (void)getLineModelListBlock:(void (^) (NSArray <LineModel *>*dataArray))block {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSString * sql = [NSString stringWithFormat:@"select * from %@ order by %@ desc",TABLE_NAME,UPDATE_TIME];
        FMResultSet *set = [db executeQuery:sql];
        
        NSMutableArray *loadArray = [NSMutableArray array];
        
        while ([set next]) {
            
            LineModel *model = [self getLineModelWithRS:set];
            
            [loadArray addObject:model];
        }
        
        [set close];
        
        if (block) {
            block(loadArray);
        }
    }];
}

+ (void)getLineModelWithUnionid:(NSString *)unionid Block:(void (^) (LineModel *lineModel))block {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inDatabase:^(FMDatabase *db) {
        
        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_NAME,UNION_ID];
        FMResultSet *set = [db executeQuery:sql,unionid];
        
        LineModel *lineModel = nil;
        
        if ([set next]) {
            
            lineModel = [self getLineModelWithRS:set];
        }
        [set close];
        
        if (block) {
            block(lineModel);
        }
    }];
}

+ (void)insertLineModel:(LineModel *)lineModel {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    [queue inDatabase:^(FMDatabase * _Nonnull db) {
        
        [self createTabWithDB:db];
        
        NSString *json = [lineModel modelToJSONString];
        
        NSDate *date = [NSDate date];
        
        NSString *insertSql = [NSString stringWithFormat:@"replace into %@(%@,%@,%@,%@,%@) values (?,?,?,?,?)",TABLE_NAME,UNION_ID,DOWNLOAD_TIME,UPDATE_TIME,JSON,SUSPEND];
        
        [db executeUpdate:insertSql,lineModel.unionid,date,date,json,@(NO)];
    }];
}

+ (void)deleteLineModelUnionid:(NSString *)unionid {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inDatabase:^(FMDatabase *db) {
        
        NSString *deleteSql = [NSString stringWithFormat:@"delete from %@ where %@ = ?",TABLE_NAME,UNION_ID];
        [db executeUpdate:deleteSql,unionid];
        
        [self deleteScenicWithUnionID:unionid db:db];
        
    }];
}

+ (void)pauseLineModelUnionid:(NSString *)unionid {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inDatabase:^(FMDatabase *db) {
        

        NSString *updatesql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",TABLE_NAME,SUSPEND,UNION_ID];
        [db executeUpdate:updatesql,@(YES),unionid];
        
    }];
}

//-----------------------------------景点表------------------------------------------
//
//
#define TABLE_SCENIC_NAME [UserManager userMd5IdentiferPath:@"scenic_list"]

#define SCENIC_PLAYPATH     @"playpath"

#define DOWNLOAD_TIME       @"download_time"// 下载时间


+ (void)createScenicTabWithDB:(FMDatabase *)db {
    
    NSString *sqlStr = [NSString stringWithFormat:@"create table if not exists %@(%@ integer not null primary key autoincrement, %@ text not null unique , %@ text, %@ date, %@ date, %@ text)",TABLE_SCENIC_NAME,SID,SCENIC_PLAYPATH,UNION_ID,DOWNLOAD_TIME,UPDATE_TIME,JSON];
    
    [db executeUpdate:sqlStr];
}

+ (ScenicPoint *)getScenicPointWithRS:(FMResultSet *)set {
    
    NSString *json = [set stringForColumn:JSON];
    
    if (json.length == 0) {
        
        return nil;
    }
    ScenicPoint *point = [ScenicPoint modelWithJSON:json];
    point.localID = @([set intForColumn:SID]);
    point.downloadTime = [set dateForColumn:DOWNLOAD_TIME];
    
    return point;
}

+ (void)getAllScenicPointWithUnionID:(NSString *)unionid Block:(void (^) (NSArray <ScenicPoint *>* scenicPointArray))block {

    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];

    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {

        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_SCENIC_NAME,UNION_ID];
        FMResultSet *set = [db executeQuery:sql,unionid];

        NSMutableArray *resultArray = [NSMutableArray array];

        while ([set next]) {

            ScenicPoint *scenicPoint = [self getScenicPointWithRS:set];

            [resultArray addObject:scenicPoint];
        }

        [set close];
        if (block) {
            block(resultArray);
        }
    }];
}

+ (void)getScenicForURL:(NSString *)URLStr Block:(void (^) (ScenicPoint *point))block {

    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];

    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {

        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_SCENIC_NAME,SCENIC_PLAYPATH];

        FMResultSet *set = [db executeQuery:sql,URLStr];

        ScenicPoint *point = nil;
        
        if ([set next]) {

            point = [self getScenicPointWithRS:set];
        }
        [set close];

        if (block) {
            block(point);
        }
    }];
}

+ (void)insertScenicPoint:(ScenicPoint *)point unionID:(NSString *)unionid db:(FMDatabase *)db {

    if (!point) {
        return;
    }
    
    [self createScenicTabWithDB:db];

    NSDate *date = [NSDate date];
    
    NSString *json = [point modelToJSONString];
    
    
    NSString *insertSql = [NSString stringWithFormat:@"replace into %@(%@,%@,%@,%@,%@) values (?,?,?,?,?)",TABLE_SCENIC_NAME,SCENIC_PLAYPATH,UNION_ID,DOWNLOAD_TIME,UPDATE_TIME,JSON];
    [db executeUpdate:insertSql, point.playpath, unionid, date, date, json];
}

+ (void)deleteScenicWithUnionID:(NSString *)unionid db:(FMDatabase *)db {

    NSString *deleteSql = [NSString stringWithFormat:@"delete from %@ where %@ = ?",TABLE_SCENIC_NAME,UNION_ID];
    [db executeUpdate:deleteSql,unionid];
}

+ (void)insertScenicArray:(NSArray *)scenicArray unionid:(NSString *)unionid {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        for (ScenicPoint *point in scenicArray) {
            
            [self insertScenicPoint:point unionID:unionid db:db];
        }
    }];
}

+ (void)getAllScenicPointBlock:(void (^) (NSArray <ScenicPoint *> *scenicArray))block {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSString * sql = [NSString stringWithFormat:@"select * from %@",TABLE_SCENIC_NAME];
        
        FMResultSet *set = [db executeQuery:sql];
        
        NSMutableArray *array = [NSMutableArray array];
        
        while ([set next]) {
            
            ScenicPoint *point = [self getScenicPointWithRS:set];
            
            if (point) {
                [array addObject:point];
            }
        }
        [set close];
        
        if (block) {
            block(array);
        }
    }];
}

@end

